<?php
/**
 * 评论的操作
 *
 * @author Legend. <xcx_legender@qq.com>
 * @param unknown
 * @return
 */

namespace Api\Event;
use Api\Manage\SysNoticeManage;

class CommentsEvent extends BaseEvent {
	/**
	 * Mongo集合的实例化
	 */
	protected $serviceObj = '';
	/**
	 * 参数初始化
	 */
	protected function _initialize() {
		parent::_initialize();
	}

	/**
	 * 对video进行评论  对content进行解析 @nickname 部分给用户发送消息
	 *
	 * @author Legend. <xcx_legender@qq.com>
	 * @param int     $vid     视频ID
	 * @param array   $user    用户信息
	 * @param string  $content 评论的内容
	 * @return
	 */
	public function add($vid, $user, $content, &$ret_data = null, $extend = []) {
		$comment = array();

		if (strlen($content) < 1) {
			return 2;
		}

		$video = A('Api/Video', 'Event')->detail($vid);
		if (empty($video)) {
			return 1;
		}

		if (empty($user['uid']) ||  $user['uid'] == 0){
			$user = [
				'uid' => 0,
				'nickname' => getVisitorName(),
			];
		}

		$comment = array(
			'video_id' => $vid,
			'uid'      => $user['uid'],
			'nickname' => $user['nickname'],
			'content'  => $content,
		);
		// 分析at人员
		$content .= ' ';
		$patter = "/@(\S*)[\s]+/";
		preg_match_all($patter, $content, $match);
		if ($match[0]) {
			$reUser = array();
			foreach ($match[0] as $key => $value) {
				$nick = trim(substr($value, 1));
				//用户@自己不推送消息
				if ($nick != $user['nickname']) {
					$reUser[] = $nick;
				}
			}
			$map = array('nickname' => array('in', $reUser));

			$reUid = A('Api/User', 'Event')->getUid($map);
			if ($reUid) {
				$reUid = array_map('intval', $reUid);
				$comment['referrer'] = $reUid;
			}
		}

		// 过滤敏感词
		A('Api/Sensitive', 'Event')->censor($comment['content']);

		// 加入到评论表
		$res = D('Common/Comments', 'Service')->addComment($comment);
		service('Video')->where(['id' => $vid])->setInc('comments', 1);


		if ($res === false) {
			return 3;
		} else {
			if ($user['uid'] > 0 && !empty($reUid)) {
				// 修改为at 提到消息
				#todo 队列
				#游客不发
				A('Api/Message', 'Event')->send('at', $vid, $user['uid'], $reUid, $res);
				// 添加发送给客户端消息 2015-6-17 15:23:17 Legend.
				// foreach ($reUid as $uid) {
					// $username[] = get_username( $uid );
				// }
				#todo 队列
				A('Api/Push', 'Event')->at($user, $reUser, $reUid, $video);
			}
			// 添加视频评论消息
			#todo 队列
			$user['uid'] > 0 && A('Api/Message', 'Event')->send('comment', $vid, $user['uid'], $video['uid'], $res);
			// $to = get_nickname($video['uid']);
			$toUser = [
				'uid'      => $video['uid'],
				'nickname' => get_nickname($video['uid']),
			];

			// 游客评论或评论自己视频不推送
			// liubo 2016-7-20
			if ($user['uid'] > 0 && $user['uid'] != $video['uid']) {
				event('Push')->videoComment($user, $toUser, $video, $comment['content']);
			}
			#D( 'Common/Video', 'Service' )->where( array( 'id'=>$vid ) )->setInc( 'comments' );
			event('Statis')->operStatisVideo($vid, $user['uid'], 'comments', 1, $extend);
			$user['uid'] > 0 && $score = event('Score')->get($user['uid'], 'comments', $vid);
			if ($score !== false) {
				$ret_data['score_plus'] = (int) $score;
			}
			SysNoticeManage::afterComment($video, $user);
			return 4;
		}

	}

	/**
	 * 根据视频标识$vid获取其所有的评论信息
	 *
	 * @param int     $vid 视频标识
	 * @author susy<susy.liang@ilongyuan.com.cn>
	 * @return array 视频评论列表
	 */
	//get($videoId, 5, '', array(), true, false, true)
	// 添加$uid参数，判断是否已经点赞 liubo 2016-06-14
	public function get($vid, $limit = '', $field = '', $filter = array(), $timeFormat = false, $uid = 0, $getTime = false) {

		$cmtService = D('Common/Comments', 'Service');

		if (empty($vid)) {
			$map = (array) $filter;
		} else {
			$map = array('video_id' => intval($vid));
			if ($filter) {
				$map = array_merge($map, (array) $filter);
			}

		}

		$map['status'] = array('egt', $cmtService::STATUS_PEDDING);

		$res = $cmtService->detail($map, $limit);

		$uEvent = A('Api/User', 'Event');
		$likeService = service('like');
		foreach ($res as $key => $value) {

			unset($value['_id']);
			$timestamp = $value['create_time'];

			if ($timeFormat) {
				$value['format_time'] = unixtime_format($timestamp);
			}
			if ($value['uid'] > 0)
			{
				$user = $uEvent->info($value['uid']);
				$value['avatar'] = empty($user['avatar'])?'':$user['avatar'];
			}else{
				$user = [
					'id' => 0,
					'nickname' => $value['nickname'],
				];
			}
			if ($uid) {
				$like = $likeService->where(['uid' => $uid, 'target_id' => $value['id'], 'type' => 3])->find();
				$value['is_zan'] = empty($like) ? 0 : 1;
			} else {
				$value['is_zan'] = 0;
			}
			$user && $value['user'] = $user;

			if (!empty($value['reward_users'])) {
				$value['reward_times'] = count($value['reward_users']) ?: 0;
				$value['reward_users'] = array_values(array_unique($value['reward_users']));
			} else {
				$value['reward_times'] = 0;
				$value['reward_users'] = [];
			}
			$list[] = $value;
		}

		if ($getTime) {
			return array('data' => $list, 'timestamp' => $timestamp);
		} else {
			return $list;
		}
	}

	/**
	 * 获取热门评论
	 * @author liubo <liubo@ilongyuan.com.cn>
	 * @param  integer $vid
	 * @param  integer $limit
	 * @param  boolean $timeFormat
	 * @param  integer $uid
	 */
	public function getHot($vid, $p = 1, $limit = 10, $timeFormat = false, $uid = 0) {

		$cmtService = D('Common/Comments', 'Service');

		$map = [
			'video_id' => intval($vid),
			'zan' => ['gt', 0],
			'status' => ['egt', $cmtService::STATUS_PEDDING],
		];

		$res = $cmtService->where($map)->page($p)->limit($limit)->order('zan desc')->select();
		$list = [];
		if (empty($res)) {
			return $list;
		}
		$uEvent = A('Api/User', 'Event');
		$likeService = service('like');
		foreach ($res as $key => $value) {

			unset($value['_id']);
			$timestamp = $value['create_time'];

			if ($timeFormat) {
				$value['format_time'] = unixtime_format($timestamp);
			}
			if ($value['uid'] > 0)
			{
				$user = $uEvent->info($value['uid']);
				$value['avatar'] = $user['avatar'];
			}else{
				$user = [
					'id' => 0,
					'nickname' => $value['nickname'],
				];
			}
			if ($uid) {
				$like = $likeService->where(['uid' => $uid, 'target_id' => $value['id'], 'type' => 3])->find();
				$value['is_zan'] = empty($like) ? 0 : 1;
			} else {
				$value['is_zan'] = 0;
			}
			$user && $value['user'] = $user;

			if (!empty($value['reward_users'])) {
				$value['reward_times'] = count($value['reward_users']) ?: 0;
				$value['reward_users'] = array_values(array_unique($value['reward_users']));
			}
			$list[] = $value;
		}
		return $list;
	}

	public function getOne($id)
	{
		static $S_COMMENT;
		if (empty($S_COMMENT[$id])){
			$cmtService = D('Common/Comments', 'Service');
			$comment = $cmtService->where(['id' => (int)$id])->find();
			unset($comment['_id']);
			$timestamp = $comment['create_time'];
			$comment['format_time'] = unixtime_format($timestamp);
			$uEvent = A('Api/User', 'Event');
			if ($comment['uid'] > 0)
			{
				$user = $uEvent->detail($comment['uid']);
				$comment['avatar'] = $user['avatar'];
			}else{
				$user = [
					'id' => 0,
					'nickname' => $comment['nickname'],
				];
			}
			$user && $comment['user'] = $user;
			$S_COMMENT[$id] = $comment;
		}
		return $S_COMMENT[$id];
	}

	/**
	 * 分页方式获取评论列表
	 * @author liubo <liubo@ilongyuan.com.cn>
	 * @param  integer $vid       视频Id
	 * @param  integer $p         页码
	 * @param  integer $pager     每页数量
	 * @param  integer $uid
	 */
	public function getByPager($vid, $p = 1, $pager = 10, $uid = 0) {
		$commentService = D('Common/Comments', 'Service');
		$condition = [
			'video_id' => $vid,
			'status'   => array('egt', $commentService::STATUS_PEDDING)
		];
		$res = $commentService->getByPager($condition, $p, $pager);

		$list = [];
		$uEvent = A('Api/User', 'Event');
		$likeService = service('like');
		foreach ($res as $key => $value) {
			unset($value['_id']);

			if ($value['uid'] > 0)
			{
				$user = $uEvent->info($value['uid']);
				$value['avatar'] = $user['avatar'];
			}else{
				$user = [
					'id' => 0,
					'nickname' => $value['nickname'],
				];
			}
			if ($uid) {
				$like = $likeService->where(['uid' => $uid, 'target_id' => $value['id'], 'type' => 3])->find();
				$value['is_zan'] = empty($like) ? 0 : 1;
			} else {
				$value['is_zan'] = 0;
			}
			$user && $value['user'] = $user;
 
			$list[] = $value;
		}
		return $list;
	}

	/**
	 * 评论总数
	 * @author liubo <liubo@ilongyuan.com.cn>
	 * @param  integer $vid 视频Id
	 */
	public function getCommentCount($vid, $query = []) {
		$commentService = D('Common/Comments', 'Service');
		if (!empty($query)) {
			$commentService->where($query);
		}
		return $commentService->countByVideo($vid);
	}

	/**
	 * 获取评论点赞的数量
	 * @author liubo <liubo@ilongyuan.com.cn>
	 */
	public function getLikeCount($cid) {
		$commentService = D('Common/Comments', 'Service');
		$comment = $commentService->where(['id' => $cid])->find();
		return $comment['zan'] ?: 0;
	}

	public function lists($query = [], $p = 1, $limit = 10)
	{
		$cService = service('Comments');
		$query['status'] = ['$gte' => $cService::STATUS_PEDDING];

		$list = $cService->where($query)->page($p)->limit($limit)->select();
		return empty($list) ? [] : array_values($list);
	}
}